In this Advance CSS tutorial, we will be going to cover the concept of Variables in CSS.
Create CSS Custom Properties using Variables
Like programming languages, we can use the concept of variables in CSS. A variable in CSS is used to store a property value to access the value using the variable name. To access the variable value, we use the
var()
function and the variable name as a parameter.
Note
: Old browser versions do not support the
var()
function, so make sure that you have the latest browser version.
How to create and use a variable in CSS
To create a variable, we should put two dashes (--) before the variable name and assign it a value that it is supposed to store. The variable name can be arbitrary, but it should be related to the value for readable code. The variable must be defined or declared inside the selector. The scope of a variable will be limited to the specified selector. If you want to make a variable that can be accessed through all the CSS selectors, then declare the variable in
:root
or
body
selector. To access the variable value, we have to use the var() function and the variable name as a parameter.
Syntax
declaring variable
accessing variable
Example
Summary
- The variable must be declared within the selector.
-
If a variable is not declared in the
:root
orbody
selector, then it will be limited to that selector only. -
If a variable is declared in the
:root
orbody
selector than any other selector can access that variable using var() function. - To declare a variable, use the double dash (--) before the variable name.
-
To access the variable, use the
var(--variable_name )
function and variable name.